<template>
  <div>
    <el-card>
      <el-form
        ref="skuFormRef"
        :model="skuFormData"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
      >
        <!-- :size="formSize" -->
        <el-form-item label="SPU 名称">
          {{ props.spu.spuName }}
        </el-form-item>
        <el-form-item label="SKU 名称" prop="skuName">
          <el-input v-model="skuFormData.skuName" placeholder="SKU 名称 " />
        </el-form-item>
        <el-form-item label="价格(元)" prop="price">
          <el-input v-model="skuFormData.price" placeholder="SKU 名称 " />
        </el-form-item>
        <el-form-item label="重量(千克)" prop="weight">
          <el-input v-model="skuFormData.weight" placeholder="SKU 名称 " />
        </el-form-item>
        <el-form-item label="规格描述" prop="skuDesc">
          <el-input
            v-model="skuFormData.skuDesc"
            type="textarea"
            placeholder="规格描述"
          />
        </el-form-item>
        <el-form-item label="平台属性" prop="skuAttrValueList">
          <el-row :gutter="10" class="row-single">
            <el-col
              :xs="8"
              :sm="6"
              :md="4"
              :lg="6"
              :xl="6"
              class="col-single"
              v-for="(attr, index) in attrList"
              :key="attr.id"
            >
              <div class="platform-item">
                <span class="platform-item-span">{{ attr.attrName }}</span>
                <el-select
                  v-model="skuFormData.skuAttrValueList[index]"
                  placeholder="请选择"
                >
                  <el-option
                    :label="attrValue.valueName"
                    :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`"
                    v-for="attrValue in attr.attrValueList"
                    :key="attrValue.id"
                  />
                </el-select>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="销售属性" prop="skuSaleAttrValueList">
          <el-row :gutter="10" class="row-single">
            <el-col
              :xs="8"
              :sm="6"
              :md="4"
              :lg="6"
              :xl="6"
              v-for="(saleAttr, index) in spuSaleAttrList"
              :key="saleAttr.id"
            >
              <div class="platform-item">
                <span class="platform-item-span">{{
                  saleAttr.saleAttrName
                }}</span>
                <el-select
                  v-model="skuFormData.skuSaleAttrValueList[index]"
                  placeholder="请选择"
                >
                  <el-option
                    :label="saleAttrValue.saleAttrValueName"
                    v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
                    :key="saleAttrValue.id"
                    :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`"
                  />
                </el-select>
              </div>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="图片列表" prop="skuImageList">
          <el-table
            :data="spuImageList"
            border
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column label="Date" width="60" type="selection" />
            <el-table-column prop="date" label="图片">
              <template v-slot="{ row }">
                <img class="imgSize" :src="row.imgUrl" alt="" />
              </template>
            </el-table-column>
            <el-table-column prop="imgName" label="名称" />
            <el-table-column prop="address" label="操作">
              <template v-slot="{ row }">
                <el-tag type="success" v-if="row.isDefault === '1'">
                  默认
                </el-tag>
                <el-button type="primary" v-else @click="setSkuDefaultImg(row)"
                  >设置默认</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(skuFormRef)"
            >保存</el-button
          >
          <el-button @click="resetForm(skuFormRef)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
export default {
  name: "SaveSku",
};
</script>

<script lang="ts" setup>
import { reactive, ref, onMounted, defineProps, defineEmits } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { useCategoryStore } from "@/stores/category";
import {
  gtePlatformAttributeApi,
  getSalesAttributeApi,
  getPictureListApi,
  addsaveSkuInfoApi,
} from "@/Api/product/sku";
import type {
  PlatformAttributeArray,
  skuSalesAttributeArray,
  skuPictureListArray,
  skuFormDataObjts,
  skuImageObjwhole,
} from "@/Api/product/model/sku";

const categoryStore = useCategoryStore();

// props 接收的参数
const props = defineProps(["spu"]);
// emit 接收的参数
const emit = defineEmits(["setIsShow"]);
// form.region
const skuFormRef = ref<FormInstance>();

// 请求回来的平台属性
const attrList = ref<PlatformAttributeArray>([]);
// 请求回来的销售属性
const spuSaleAttrList = ref<skuSalesAttributeArray>([]);
// 请求回来的 图片列表
const spuImageList = ref<skuPictureListArray>([]);

const skuFormData = reactive<skuFormDataObjts>({
  skuName: "",
  price: 0,
  weight: 0,
  skuDesc: "",
  skuAttrValueList: [
    // {
    //   attrId: 0, // 属性id
    //   attrName: "string", // 属性名
    //   valueId: 0, // 属性值id
    //   valueName: "string", // 属性值名称
    // },
  ],
  skuSaleAttrValueList: [
    // {
    //   saleAttrId: 0, // 销售属性id
    //   saleAttrName: "string", // 销售属性名称
    //   saleAttrValueId: 0, // 销售属性值id
    //   saleAttrValueName: "string", // 销售属性值名称
    // },
  ],
  skuImageList: [
    // {
    //   imgName: "string",
    //   imgUrl: "string",
    //   isDefault: "string",
    // },
  ],
  skuDefaultImg: "",
});

// 挂在的时候发送平台属性请求   请求回来的数据赋值给需要放回来的数据  响应式 变量接收
onMounted(async () => {
  const { category1Id, category2Id, category3Id } = categoryStore;
  attrList.value = await gtePlatformAttributeApi(
    category1Id as number,
    category2Id as number,
    category3Id as number
  );
});

onMounted(async () => {
  spuSaleAttrList.value = await getSalesAttributeApi(props.spu.id);
});

onMounted(async () => {
  spuImageList.value = await getPictureListApi(props.spu.id);
});

// 表单的自定义表单验证  回调函数需要写在 表单验证的 前面  声明了回调才能可以直接用
const skuImageListValidator = (rule: any, value: any, callback: any) => {
  // value 就是你校验的那个变量 那个属性
  if (!value.length) {
    callback("请至少选择一张图片");
    return;
  }
  if (!skuFormData.skuDefaultImg) {
    callback("请至少选择一张默认图片");
    return;
  }
  // 这是这个回调的放行回调函数  这个回调函数不调用  程序后面的代码都不会再执行  就相当于 await 了一个pedding 进行中
  callback();
};

const rules = reactive<FormRules>({
  skuName: [{ required: true, message: "请输入SKU名称", trigger: "blur" }],
  price: [{ required: true, message: "请输入SKU价格", trigger: "blur" }],
  weight: [{ required: true, message: "请输入SKU的重量", trigger: "blur" }],
  skuDesc: [{ required: true, message: "请输入SKU规则描述", trigger: "blur" }],
  skuAttrValueList: [{ required: true, message: "请选择SKP平台属性" }],
  skuSaleAttrValueList: [{ required: true, message: "请选择SKU销售属性" }],
  skuImageList: [{ required: true, validator: skuImageListValidator }],
});

// 保存按钮 给sku添加数据的回调
const submitForm = async (formEl: FormInstance | undefined) => {
  // 表单验证   需要表单验证回来  这个回调才会返回一个成功的
  await skuFormRef.value?.validate();

  await addsaveSkuInfoApi({
    ...skuFormData,
    skuSaleAttrValueList: skuFormData.skuSaleAttrValueList
      .filter(Boolean)
      .map((attr) => {
        const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] =
          attr.split(":");

        return {
          saleAttrId: +saleAttrId, // 销售属性id
          saleAttrName, // 销售属性名称
          saleAttrValueId: +saleAttrValueId, // 销售属性值id
          saleAttrValueName, // 销售属性值名称
        };
      }),
    skuAttrValueList: skuFormData.skuAttrValueList
      .filter(Boolean)
      .map((attr) => {
        const [attrId, attrName, valueId, valueName] = attr.split(":");
        return {
          attrId: +attrId, // 属性id
          attrName, // 属性名
          valueId: +valueId, // 属性值id
          valueName, // 属性值名称
        };
      }),
    spuId: props.spu.id,
    category3Id: categoryStore.category3Id as number,
  });
  emit("setIsShow", 1);
};

// 取消按钮 跳回spuTable页面
const resetForm = (formEl: FormInstance | undefined) => {
  // console.log(1);
  emit("setIsShow", 1);
};

//图片的选中触发的change事件的回调函数
const handleSelectionChange = (val: skuPictureListArray) => {
  skuFormData.skuImageList = val;
};

// 图片列表的默认选中的回调函数
const setSkuDefaultImg = (row: skuImageObjwhole) => {
  //  默认图片只能有一张  需要排他思想来写
  console.log(row);

  spuImageList.value.forEach((img) => {
    img.isDefault = "0";
  });
  row.isDefault = "1";
  // console.log(row);
  skuFormRef.value?.clearValidate("skuImageList");
  skuFormData.skuDefaultImg = row.imgUrl;
};
</script>

<style scoped>
.platform-item {
  display: flex;
}
.platform-item-span {
  margin-right: 10px;
}
.row-single {
  width: 100%;
}
.col-single {
  margin-bottom: 20px;
}
.imgSize {
  width: 200px;
  height: 100px;
}
</style>
